<?php

namespace app\service;

use app\controller\Image;
use app\controller\Statistics;
use app\model\CluePerson;
use app\model\OrderEnterpriseExchange;
use app\model\OrderPersonCertificateRegister;
use app\model\OrderTransactionRecord;
use think\facade\Cache;

class RedisService
{

    protected $redis;

    public function __construct()
    {
        // 连接redis
        $this->redis = Cache::store('redis');
    }

    /**
     * 获取线索库人才库缓存
     * @param $dataId
     * @param $uid
     * @return mixed
     */
    public function getPersonDataReSet($dataId,$uid)
    {
        $personModel = new CluePerson();
        $clue = new Clue();

        if(empty($dataId)){
            return [];
        }

        if ($this->redis->exists('clue_person')){
            foreach ($dataId as $person_id) {

                if (!$this->redis->hget('clue_person',$person_id)){
                    $personData = $personModel->redisGetIdPersonInfo ($person_id);
                    $this->redis->hset('clue_person',$personData['id'],json_encode ($clue->personData($personData,$uid)));
                }
            }
        }else{
            foreach ($dataId as $person_id) {
                $personData = $personModel->redisGetIdPersonInfo ($person_id);
                $this->redis->hset('clue_person',$personData['id'],json_encode ($clue->personData($personData,$uid)));
            }
        }

        //获取最终数据
        $list = $this->redis->hMget('clue_person',$dataId);

        if ($list){
            //json值转arr
            return array_map (static function ($val){
                return json_decode ($val,true)[0];
            },array_values ($list));
        }

        return [];
    }

    /**
     * 线索库人才库更新
     * @param $data
     * @param $uid
     * @return bool
     */
    public function updatePersonData($data,$uid)
    {
        $clue = new Clue();
        if (!$data){
            return false;
        }
        if ($this->redis->exists('clue_person')){
            if ($this->redis->hget('clue_person',$data['id'])){
                $this->redis->hset('clue_person',$data['id'],json_encode ($clue->personData($data,$uid)));
            }
        }
        return true;
    }

    /**
     * 线索库人才库删除
     * @param $id
     * @return bool
     */
    public function delPersonData($id)
    {
        if (!$id) return false;

        if ($this->redis->exists('clue_person')){
            if ($this->redis->hget('clue_person',$id)){
                $this->redis->hdel('clue_person',$id);
            }
        }
        return true;
    }

    /**
     * 线索库 企业库缓存数据
     * @param $dataId
     * @param $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getEnterData($dataId,$uid)
    {
        $enterModel = new \app\model\ClueEnterprise();
        $clue = new Clue();
        $certificate = new Certificate();

        if(empty($dataId)){
            return [];
        }

        if ($this->redis->exists('clue_enter')){
            foreach ($dataId as $person_id) {
                if (!$this->redis->hget('clue_enter',$person_id)){
                    $enterData = $enterModel->getIdInfo ($person_id);
                    $this->redis->hset('clue_enter',$enterData['id'],json_encode ($clue->enterData ($certificate->arrFindMobile($enterData),$uid)));
                }
            }
        }else{
            foreach ($dataId as $person_id) {

                $enterData = $enterModel->getIdInfo ($person_id);

                $this->redis->hset('clue_enter',$enterData['id'],json_encode ($clue->enterData ($certificate->arrFindMobile($enterData),$uid)));
            }
        }
        //获取最终数据
        $list = $this->redis->hMget('clue_enter',$dataId);

        if ($list){
            //json值转arr
            return array_map (static function ($val){
                return json_decode ($val,true)[0];
            },array_values ($list));
        }

        return [];
    }

    /**
     * 删除企业库缓存数据
     * @param $id
     * @return bool
     */
    public function delEnterData($id)
    {
        if (!$id) return false;

        if ($this->redis->exists('clue_enter')){
            if ($this->redis->hget('clue_enter',$id)){
                $this->redis->hdel('clue_enter',$id);
            }
        }
        return true;
    }

    /**
     * 获取区域多级tree缓存
     * @return array|string
     */
    public function getAreaData()
    {
        if ($this->redis->exists('system_area')){
//            print_r ($this->redis->hgetall ('system_area')['area']);die;
            return json_decode ($this->redis->hgetall ('system_area')['area'],true);
        }
        return '';
    }

    public function setAreaData($data)
    {
        return $this->redis->hset('system_area','area',json_encode ($data));
    }

    /**
     * 获取订单证书审核列表
     * @param $dataId
     * @param $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderZsshData($dataId, $uid)
    {
        $orderPersonCertificateRegisterModel = new OrderPersonCertificateRegister();
        $orderSer = new Order();

        if(empty($dataId)){
            return [];
        }

        if ($this->redis->exists('order_zssh')){
            foreach ($dataId as $id) {
                if (!$this->redis->hget('order_zssh',$id)){
                    $orderData = $orderPersonCertificateRegisterModel->getIdDetails ($id);
                    $data = $orderSer->whDingshiqi($orderData);
                    $this->redis->hset('order_zssh',$id,json_encode ($data));
                }
            }
        }else{
            foreach ($dataId as $id) {
                $orderData = $orderPersonCertificateRegisterModel->getIdDetails ($id);
                $data = $orderSer->whDingshiqi($orderData);
                $this->redis->hset('order_zssh',$id,json_encode ($data));
            }
        }

        //获取最终数据
        $list = $this->redis->hMget('order_zssh',$dataId);
        if ($list){
            //json值转arr
            return array_map (static function ($val){
                return json_decode ($val,true);
            },array_values ($list));
        }
        return [];
    }

    /**
     * 更新证书审核订单缓存
     */
    public function updateOrderZsshData($id)
    {
        $orderPersonCertificateRegisterModel = new OrderPersonCertificateRegister();
        $orderSer = new Order();

        if (!$id){
            return false;
        }

        if ($this->redis->exists('order_zssh')){
            $orderData = $orderPersonCertificateRegisterModel->getIdDetails ($id);
            $data = $orderSer->whDingshiqi($orderData);
            //如果没有该数据 该删除掉缓存
            if (!$data){
                $this->redis->hdel('order_zssh',$id);
            }
            $this->redis->hset('order_zssh',$id,json_encode ($data));
        }
        return true;
    }

    /**
     * 删除证书审核订单缓存
     */
    public function deleteOrderZsshData($id)
    {
        if (!$id){
            return false;
        }
        if (is_array ($id)){
            foreach ($id as $i) {
                if ($this->redis->exists('order_zssh')){
                    $this->redis->hdel('order_zssh',$i);
                }
             }
        }else{
            if ($this->redis->exists('order_zssh')){
                $this->redis->hdel('order_zssh',$id);
            }
        }

        return true;
    }


    /**
     * 订单管理列表
     * @illustrate redis hashKey 用”订单编号“拼接”销售时间“戳来确定唯一性，因为牵扯到退单完成数据ID等其他信息重复
     * @param $dataId //数据ID
     * @param $uid //用户登陆标示
     * @param string $reKey //查询订单管理缓存标示  order_dz 倒证  order_gszs 公司证书 order_zsbl 证书办理 order_qyzs 证书办理企业证书
     */

    public function getOrderReKeyDataList($dataId, $uid, string $reKey="order_dz"): array
    {
        $orderSer = new Order();
        if(empty($dataId)){
            return [];
        }


        $saleRedisKeyData = [];//用于redis获取
        if ($this->redis->exists($reKey)){
            foreach ($dataId as $item) {
                if (isset($item['sale_date'])){
                    if (!empty($item['sale_date'])){
                        $saleData = strtotime ($item['sale_date']);
                    }else{
                        $saleData = '';
                    }
                }else{
                    $saleData = '';
                }
                //拼接最终redis查询key数组
                $saleCode = $item['certificate_code'].'-'.$saleData;
                $saleRedisKeyData[] = $saleCode;

                if (!$this->redis->hget($reKey,$saleCode)){
                    //拼接完整数据
                    if ($reKey == 'order_gszs'){
                        $orderData = $orderSer->suppOrderGszsInfo ($item);
                    }elseif ($reKey == 'order_dz'){
                        $orderData = $orderSer->suppOrderDzInfo ($item['id'],$uid);
                    }
                    /**
                     * 二维数据 不确定是否包含退单内容
                     */
                    foreach ($orderData as $orderDatum) {
                        //订单编号拼接销售时间确定key唯一性
                        $saleCodes = $orderDatum['certificate_code'].'-'.strtotime ($orderDatum['sale_date']);
                        if (!empty($orderDatum)){
                            $this->redis->hset($reKey,$saleCodes,json_encode ($orderDatum));
                        }
                    }

                }
            }
        }else{
            foreach ($dataId as $item) {
                if (isset($item['sale_date'])){
                    if (!empty($item['sale_date'])){
                        $saleData = strtotime ($item['sale_date']);
                    }else{
                        $saleData = '';
                    }
                }else{
                    $saleData = '';
                }
                //拼接最终redis查询key数组
                $saleRedisKeyData[] = $item['certificate_code'].'-'.$saleData;
                //拼接完整数据
                if ($reKey == 'order_gszs'){
                    $orderData = $orderSer->suppOrderGszsInfo ($item);
                }elseif ($reKey == 'order_dz'){
                    $orderData = $orderSer->suppOrderDzInfo ($item['id'],$uid);
                }

                /**
                 * 二维数据 不确定是否包含退单内容
                 */
                foreach ($orderData as $orderDatum) {

                    if (isset($orderDatum['sale_date'])){
                        if (!empty($orderDatum['sale_date'])){
                            $saleData = strtotime ($orderDatum['sale_date']);
                        }else{
                            $saleData = '';
                        }
                    }else{
                        $saleData = '';
                    }

                    //订单编号拼接销售时间确定key唯一性
                    $saleCode = $orderDatum['certificate_code'].'-'.$saleData;
                    if ($orderDatum){
                        $this->redis->hset($reKey,$saleCode,json_encode ($orderDatum));
                    }
                }
            }
        }

        //获取最终数据
        $list = $this->redis->hMget($reKey,$saleRedisKeyData);
        if ($list){
            //json值转arr
            return array_map (static function ($val){
                return json_decode ($val,true);
            },array_values ($list));
        }
        return [];
    }

    /**
     * 删除订单列表缓存
     * @param $dataId //order信息
     * @param string $reKey
     * @return bool
     */
    public function delOrderDzData($dataId, string $reKey)
    {
        if (!$dataId || !$reKey){
            return false;
        }

        if (isset($dataId['sale_date'])){
            if (!empty($dataId['sale_date'])){
                $saleData = strtotime ($dataId['sale_date']);
            }else{
                $saleData = '';
            }
        }else{
            $saleData = '';
        }

        if ($this->redis->exists($reKey)){
            //拼接订单编号销售时间
            $saleCode = $dataId['certificate_code'].'-'.$saleData;

            $this->redis->hdel($reKey,$saleCode);
        }
        return true;
    }

    /**
     * 订单管理-公司证书列表
     */

    /**
     * 订单管理-企业证书列表
     */

    /**
     * 订单管理-证书办理列表
     */

    /**
     * 财务管理-业绩总表列表
     */
    public function getPerformanceList($dataId,$uidArr,$uid)
    {
        $financeSer = new FinanceServer();
        $reKey = "finance_list";

        if(empty($dataId)){
            return [];
        }

        $saleRedisKeyData = [];//用于redis获取
        if ($this->redis->exists($reKey)){
            foreach ($dataId as $item) {
                //拼接最终redis查询key数组
                $saleCode = $item['certificate_code'].'-'.strtotime ($item['sale_date']);

                if (!$this->redis->hget($reKey,$saleCode)){

                    //拼接完整数据
                    $orderData = $financeSer->getEachDetails ($item['id'],$item['certificate_code'],$item,$uidArr);

                    if ($orderData){
                        $saleRedisKeyData[] = $saleCode;
                        //订单编号拼接销售时间确定key唯一性
                        $saleCodes = $item['certificate_code'].'-'.strtotime ($item['sale_date']);
                        $this->redis->hset($reKey,$saleCodes,json_encode ($orderData));
                    }
                }else{
                    $saleRedisKeyData[] = $saleCode;
                }
            }
        }else{
            foreach ($dataId as $item) {
                //拼接完整数据
                $orderData = $financeSer->getEachDetails ($item['id'],$item['certificate_code'],$item,$uidArr);
                if ($orderData){
                    //拼接最终redis查询key数组
                    $saleRedisKeyData[] = $item['certificate_code'].'-'.strtotime ($item['sale_date']);
                    //订单编号拼接销售时间确定key唯一性
                    $saleCode = $item['certificate_code'].'-'.strtotime ($item['sale_date']);
                    $this->redis->hset($reKey,$saleCode,json_encode ($orderData));
                }
            }
        }

        //获取最终数据
        if (!$saleRedisKeyData){
            return [];
        }
        $list = $this->redis->hMget($reKey,$saleRedisKeyData);
        if ($list){
            //json值转arr
            return array_map (static function ($val){
                return json_decode ($val,true);
            },array_values ($list));
        }
        return [];
    }

    /**
     * 删除业绩总表缓存
     */
    public function delPerformance(?array $dataId)
    {
        $reKey = "finance_list";
        if (!$dataId){
            return false;
        }

        if (isset($dataId['sale_date'])){
            if (!empty($dataId['sale_date'])){
                $saleData = strtotime ($dataId['sale_date']);
            }else{
                $saleData = '';
            }
        }else{
            $saleData = '';
        }

        if ($this->redis->exists($reKey)){
            //拼接订单编号销售时间
            $saleCode = $dataId['certificate_code'].'-'.$saleData;
            $this->redis->hdel($reKey,$saleCode);
        }
        return true;
    }

    /**
     * 财务管理-收付款列表缓存
     */
    public function getTransactionReList($dataId)
    {
        $OrderTransactionRecordModel = new OrderTransactionRecord();
        $orderSer = new Order();

        $reKey = "ransaction_record";
        if(empty($dataId)){
            return [];
        }

        if (!is_array ($dataId)){
            $dataId = explode (',',$dataId);
        }

        if ($this->redis->exists($reKey)){
            foreach ($dataId as $id) {
                if (!$this->redis->hget($reKey,$id)){
                    $orderData = $OrderTransactionRecordModel->getTransactionIdListModel ($id);
                    $data = $orderSer->addTransactionField($orderData);
                    /**
                     * 如果是二维数组 转一维数据
                     */
                    if (!is_one_dimensional_array ($data)){
                        $data = $data[0];
                    }
                    $this->redis->hset($reKey,$id,json_encode ($data));
                }
            }
        }else{
            foreach ($dataId as $id) {
                $orderData = $OrderTransactionRecordModel->getTransactionIdListModel ($id);
                $data = $orderSer->addTransactionField($orderData);
                /**
                 * 如果是二维数组 转一维数据
                 */
                if (!is_one_dimensional_array ($data)){
                    $data = $data[0];
                }
                $this->redis->hset($reKey,$id,json_encode ($data));
            }
        }

        //获取最终数据
        $list = $this->redis->hMget($reKey,$dataId);
        if ($list){
            //json值转arr
            return array_map (static function ($val){
                return json_decode ($val,true);
            },array_values ($list));
        }
        return [];
    }

    /**
     * 收付款列表删除
     */
    public function delTransactionId($id)
    {
        if (!$id){
            return false;
        }
        $redisKey = "ransaction_record";
        if ($this->redis->exists($redisKey)){
            $this->redis->hdel($redisKey,$id);
        }
        return true;
    }



    /**
     * 报表中心-业绩统计
     */
    public function getStatisticsPerformance($start,$end)
    {
        $statisticsService = new \app\service\Statistics();
        $userModel = new \app\model\User();
        $uidData = $userModel->getIdUserFieldRandInfo ($userModel->getAllUidsModel (),'','',$start,$end);
        $reKey = "statistics_performance";
        //判断时间区间是否成立
        if (empty($start) || empty($end)){
            return [];
        }

        //取时间区间的每天的00:00:00时间戳
        $startStamp = strtotime ($start);
        $endStamp = strtotime ($end.'23:59:59');
        //如果是当天 不计缓存
        if ($startStamp == strtotime (date('y-m-d'))){
            return [];
        }

        $timeMap = [];//用于取hashKey
        while (true){
            if ($startStamp >= $endStamp || $startStamp >= strtotime (date('y-m-d'))){
                break;
            }
            $timeMap[] = $startStamp;
            if ($this->redis->exists($reKey)){
                if (!$this->redis->hget($reKey,$startStamp)){
                    $this->redis->hset($reKey,$startStamp,json_encode ($statisticsService->getUidDataPerformanceData ($uidData,$startStamp,$startStamp+86399)));
                }
            }else{
                //如果没有key 获取时间当天内容 创建key
                $this->redis->hset($reKey,$startStamp,json_encode ($statisticsService->getUidDataPerformanceData ($uidData,$startStamp,$startStamp+86399)));
            }
            $startStamp += 86400;
        }

        /**
         * 取key数据
         */
        if (empty($timeMap)){
            return [];
        }
        $list = $this->redis->hMget($reKey,$timeMap);

        if ($list){
            //json值转arr
            return array_map (static function ($val){
                return json_decode ($val,true);
            },array_values ($list));
        }
        return [];
    }


    /**
     * 报表中心-业绩统计-姓名部门更新
     */
    public function updateStatisticsPerformanceUserInfo($userData)
    {
        $reKey = "statistics_performance";
        //获取所有缓存
        $data = $this->redis->hgetAll($reKey);

        if ($data){
            //json值转arr
            return array_map (static function ($val) use ($userData){
                $systemService = new System();
                $findData = json_decode ($val,true);

                foreach ($findData as $findDatum) {

                    if ($findDatum['id'] == $userData['id']){
                        $findDatum['nickname'] = $userData['nickname'];
                        $findDatum['department_id'] = $systemService->getOrgStrName($userData['department_id']['id']);
                    }
                 }
            },array_values ($data));
        }
    }

    /**
     * 报表中心-业绩统计-更新时间区间统计
     */
    public function updateDateBetweenData($start,$end)
    {
        $userModel = new \app\model\User();
        $uidData = $userModel->getIdUserFieldRandInfo ($userModel->getAllUidsModel (),'','',$start,$end);
        $statisticsService = new \app\service\Statistics();
        $reKey = "statistics_performance";
        //判断时间区间是否成立
        if (empty($start) || empty($end)){
            return [];
        }

        //取时间区间的每天的00:00:00时间戳
        $startStamp = strtotime ($start);
        $endStamp = strtotime ($end.'23:59:59');
        //如果是当天 不计缓存
        if ($startStamp == strtotime (date('y-m-d'))){
            return [];
        }
        $timeMap = [];//用于取hashKey

        while (true){
            if ($startStamp >= $endStamp){
                break;
            }
            $timeMap[] = $startStamp;
            if ($this->redis->exists($reKey)){
                if (!$this->redis->hget($reKey,$startStamp)){
                    $this->redis->hset($reKey,$startStamp,json_encode ($statisticsService->getUidDataPerformanceData ($uidData,$startStamp,$startStamp+86399)));
                }else{
                    $this->redis->hdel($reKey,$startStamp);
                }
            }else{
                //如果没有key 获取时间当天内容 创建key
                $this->redis->hset($reKey,$startStamp,json_encode ($statisticsService->getUidDataPerformanceData ($uidData,$startStamp,$startStamp+86399)));
            }

            $startStamp += 86400;
        }
    }


    /**
     * 报表中心-收付款流水列表
     */
    public function getFlowingList(array $ids)
    {
        $statisticsSer = new \app\service\Statistics();
        $redisKey = "statistics_flowing_water";

        if(empty($ids)){
            return [];
        }

        if ($this->redis->exists($redisKey)){
            foreach ($ids as $id) {
                if (!$this->redis->hget($redisKey,$id)){
                    $fieldData = $statisticsSer->supField ($id);
                    $this->redis->hset($redisKey,$fieldData['id'],json_encode ($fieldData));
                }
            }
        }else{
            foreach ($ids as $id) {
                $fieldData = $statisticsSer->supField ($id);
                $this->redis->hset($redisKey,$fieldData['id'],json_encode ($fieldData));
            }
        }

        //获取最终数据
        $list = $this->redis->hMget($redisKey,$ids);
        if ($list){
            //json值转arr
            return array_map (static function ($val){
                return json_decode ($val,true);
            },array_values ($list));
        }
        return [];
    }

    /**
     * 报表中心-收付款流水缓存删除
     */
    public function delFlowingId($id)
    {
        $redisKey = "statistics_flowing_water";
        if (!$id){
            return false;
        }
        if ($this->redis->exists($redisKey)){
            $this->redis->hdel($redisKey,$id);
        }
        return true;
    }


}